﻿Imports System.IO
Imports System.Xml

Public Class Form1
    Private Sub OpenDataFolderToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenDataFolderToolStripMenuItem.Click
        OpenDataFolder()
    End Sub
    Private Sub LocationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LocationToolStripMenuItem.Click
        MsgBox(My.Application.Info.DirectoryPath)
    End Sub
    Private Sub VersionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VersionToolStripMenuItem.Click
        MsgBox(My.Application.Info.Version.ToString, MsgBoxStyle.Information, My.Application.Info.Title + " Version")
    End Sub
    Private Sub FIMServerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FIMServerToolStripMenuItem.Click
        FIMServerSettings.Show()
    End Sub

    Private Sub PowerShellScriptToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PowerShellScriptToolStripMenuItem.Click
        ShowScriptCode()
    End Sub
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        WebBrowser.Navigate("about:blank")
        ToolStripStatusLabel1.Text = "Ready"

        ' Load values from the application settings file
        FIMServer = My.Settings.FIMServer

        If Not (String.IsNullOrEmpty(My.Settings.Username) And String.IsNullOrEmpty(My.Settings.Password)) Then
            AlternativeUsername = My.Settings.Username
            Dim decryptedPassword = DecryptString(My.Settings.Password)
            Dim securePassword As Security.SecureString = New Security.SecureString
            For i As Integer = 0 To decryptedPassword.Length - 1
                securePassword.AppendChar(decryptedPassword.Chars(i))
            Next
            AlternativePassword = securePassword
        End If
    End Sub
    Private Sub ExportToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportToolStripMenuItem.Click
        StartScript("GetData.ps1")
    End Sub

    Private Sub GetDataButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GetDataButton.Click
        StartScript("GetData.ps1")
    End Sub

    Private Sub CopyToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyToolStripMenuItem.Click
        CopyToClipboard()
    End Sub

    Private Sub CopyButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyButton.Click
        CopyToClipboard()
    End Sub

    Private Sub AttributeFlowPrecedenceButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AttributeFlowPrecedenceButton.Click
        DisplayNames("Attribute Flow Precedence")
    End Sub

    Private Sub AttributeFlowPrecedenceToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AttributeFlowPrecedenceToolStripMenuItem.Click
        DisplayNames("Attribute Flow Precedence")
    End Sub

    Private Sub SetsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SetsToolStripMenuItem.Click
        DisplayNames("Sets")
    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        DisplayNames("Management Agents")
    End Sub

    Private Sub ManagementAgentsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ManagementAgentsToolStripMenuItem.Click
        DisplayNames("Management Agents")
    End Sub

    Private Sub MetaverseSchemaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MetaverseSchemaToolStripMenuItem.Click
        DisplayObject("MetaverseSchema", "", False)
    End Sub

    Private Sub FIMMASchemaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FIMMASchemaToolStripMenuItem.Click
        DisplayObject("FIMMaSchema", "", False)
    End Sub

    Private Sub ActiveMetaverseSchemaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ActiveMetaverseSchemaToolStripMenuItem.Click
        DisplayObject("ActiveMVSchema", "", False)
    End Sub

    Private Sub SynchronizationRulesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SynchronizationRulesToolStripMenuItem.Click
        DisplayNames("Synchronization Rules")
    End Sub

    Private Sub SynchronizationRulesButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SynchronizationRulesButton.Click
        DisplayNames("Synchronization Rules")
    End Sub

    Private Sub WorkflowsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles WorkflowsToolStripMenuItem.Click
        DisplayNames("Workflows")
    End Sub

    Private Sub WorkflowsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles WorkflowsButton.Click
        DisplayNames("Workflows")
    End Sub

    Private Sub ManagementPolicyRuleToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ManagementPolicyRuleToolStripMenuItem.Click
        DisplayNames("Management Policy Rules")
    End Sub

    Private Sub ManagementPolicyRules_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ManagementPolicyRules.Click
        DisplayNames("Management Policy Rules")
    End Sub

    Private Sub ReplicationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReplicationToolStripMenuItem.Click
        DisplayObject("Replication", "", False)
    End Sub

    Private Sub OpenDataFileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenDataFileToolStripMenuItem.Click
        LoadDataFile()
    End Sub

    Private Sub LoadDataFile()
        OpenDataFileDialog.Title = "Select a Data file"
        OpenDataFileDialog.Filter = "XML files (*.xml)|*.xml"
        OpenDataFileDialog.InitialDirectory = "C:\"
        OpenDataFileDialog.ShowReadOnly = True

        Dim defaultDataFile As String = My.Application.Info.DirectoryPath & "\Res\Data\Data.xml"

        If OpenDataFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            Try
                Dim fileName As String = OpenDataFileDialog.FileName
                If Not String.IsNullOrEmpty(fileName) Then
                    DataXmlFilePath = fileName
                End If

                Dim result = MsgBox("Would you like to overwrite the default data file (" & defaultDataFile & ") ?", MsgBoxStyle.YesNo, "Overwrite default data file")
                If result = MsgBoxResult.Yes Then
                    File.Copy(fileName, defaultDataFile, True)
                End If
            Catch ex As Exception
                MessageBox.Show("Cannot read data file from disk. Original error: " & ex.Message)
            End Try
        End If
    End Sub

    Private Sub DisplayObject(ByVal ObjectType As String, ByVal Filter As String, ByVal IsId As Boolean)
        Try
            If IsId Then
                Filter = "urn:uuid:" + Filter
            End If

            Dim xslFile As String = ""

            Select Case ObjectType
                Case "SynchronizationRule"
                    xslFile = "Synchronization Rules.XSLT"
                Case "MetaverseSchema"
                    xslFile = "Metaverse Schema.XSLT"
                Case "FIMMaSchema"
                    xslFile = "FIMMA Schema.XSLT"
                Case "ManagementPolicyRule"
                    xslFile = "Management Policy Rules.XSLT"
                Case "ma-data"
                    xslFile = "Management Agents.XSLT"
                Case "Replication"
                    xslFile = "Replication.XSLT"
                Case "ActiveMVSchema"
                    xslFile = "Active Metaverse Schema.XSLT"
                Case "WorkflowDefinition"
                    xslFile = "Workflows.XSLT"
                Case "AttributeFlowPrecedence"
                    xslFile = "Attribute Flow Precedence.XSLT"
                Case "Set"
                    xslFile = "Sets.XSLT"
                Case Else
                    Throw New Exception("Invalid type in DisplayObject!")
            End Select

            Me.Cursor = Cursors.AppStarting
            ToolStripStatusLabel1.Text = "Rendering Data..."

            Dim xmlFilePath As String = GetXmlFilePath()
            Dim xmlDoc As New XmlDocument
            xmlDoc.Load(xmlFilePath)
            WebBrowser.DocumentText = Transform(xslFile, xmlDoc, Filter)

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, My.Application.Info.Title)
        Finally
            ToolStripStatusLabel1.Text = "Ready"
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub DisplayNames(ByVal Type As String)
        Try
            Dim xmlFilePath As String = GetXmlFilePath()
            Dim xmlDoc1 As New XmlDocument
            xmlDoc1.Load(xmlFilePath)

            Dim filter As String = ""
            Select Case Type
                Case "Synchronization Rules"
                    filter = "SynchronizationRule"
                Case "Workflows"
                    filter = "WorkflowDefinition"
                Case "Management Policy Rules"
                    filter = "ManagementPolicyRule"
                Case "Management Agents"
                    filter = "ma-data"
                Case "Sets"
                    filter = "Set"
                Case "Attribute Flow Precedence"
                    filter = "Attribute Flow Precedence"
                Case Else
                    Throw New Exception("Unknown menu option")
            End Select

            Me.Cursor = Cursors.AppStarting
            ToolStripStatusLabel1.Text = "Rendering data..."
            WebBrowser.DocumentText = Transform("Display Names.XSLT", xmlDoc1, filter)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, My.Application.Info.Title)
        Finally
            ToolStripStatusLabel1.Text = "Ready"
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub WebBrowser_Navigating(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserNavigatingEventArgs) Handles WebBrowser.Navigating
        If (e.Url.OriginalString = "about:blank") Then
            Exit Sub
        End If

        e.Cancel = True
        Dim arrCmd As String() = e.Url.OriginalString.Split(":")

        Select Case arrCmd(1)
            Case "Set"
                DisplayObject(arrCmd(1), arrCmd(2), True)
            Case "SynchronizationRule"
                DisplayObject(arrCmd(1), arrCmd(2), True)
            Case "WorkflowDefinition"
                DisplayObject(arrCmd(1), arrCmd(2), True)
            Case "ManagementPolicyRule"
                DisplayObject(arrCmd(1), arrCmd(2), True)
            Case "ma-data"
                DisplayObject(arrCmd(1), arrCmd(2), True)
            Case "AttributeFlowPrecedence"
                DisplayObject("AttributeFlowPrecedence", arrCmd(2), False)
            Case Else
                Throw New Exception("Unknown menu option")
        End Select
    End Sub

    Private Sub CopyToClipboard()
        Try
            '-------------------------------------------------------------------------------------------------
            If IsNothing(WebBrowser.Document.GetElementById("tData")) Then
                MsgBox("There is no object to copy", MsgBoxStyle.Information, My.Application.Info.Title)
                Exit Sub
            End If
            '-------------------------------------------------------------------------------------------------
            Me.Cursor = Cursors.AppStarting

            WebBrowser.Document.ExecCommand("SelectAll", False, Nothing)
            WebBrowser.Document.ExecCommand("Copy", False, Nothing)
            WebBrowser.Document.ExecCommand("Unselect", False, Nothing)

            MsgBox("Data successfully copied to clipboard", MsgBoxStyle.Information, My.Application.Info.Title)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, My.Application.Info.Title)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub StartScript(ByVal scriptName As String)
        Try
            Me.Cursor = Cursors.AppStarting
            ToolStripStatusLabel1.Text = "Retrieving data..."

            RunPSScript(scriptName, "")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, My.Application.Info.Title)
        Finally
            ToolStripStatusLabel1.Text = "Ready"
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub ShowScriptCode()
        Try
            '----------------------------------------------------------------------------------------------
            Dim scriptPath As String = My.Application.Info.DirectoryPath & "\Res\PowerShell\GetData.ps1"
            If Not File.Exists(scriptPath) Then
                Throw New Exception("PowerShell script not found: " + vbCrLf + scriptPath)
            End If
            '----------------------------------------------------------------------------------------------
            Dim fileText As String = ""
            Dim streamReader As New StreamReader(scriptPath)

            Do While streamReader.Peek <> -1
                fileText += streamReader.ReadLine
                fileText += "<br>"
            Loop

            WebBrowser.DocumentText = fileText
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, My.Application.Info.Title)
        End Try
    End Sub

End Class
